#include "calServer.hpp"
#include <memory>

using namespace std;
using namespace server;


static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " serverip serverport\n\n";
}
// ./tcpclient serverip serverport
string suffixToDesc(const string suffix) {
    std::string ct = "Content-Type: ";
    if (suffix == ".html") {         // 注意后缀是 `.html` 而非 `./html`
        ct += "text/html";           // 修正拼写错误
    } else if (suffix == ".jpg") {
        ct += "image/jpeg";
    } else if (suffix == ".ico") {
        ct += "image/x-icon";
    } else {
        ct += "text/plain";          // 添加默认类型
    }
    ct += "\r\n";
    return ct;
}

bool Get(const httpRequest &req,httpResponse &resp)//对客户端提供服务的函数
{   cout << "----------------------http start---------------------------" << endl;
    std::cout << req.message << std::endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpversion: " << req.httpversion << std::endl;
    std::cout << "path:"<<req.path<<std::endl;
    std::cout << "suffix:"<<req.suffix<<std::endl;
    std::cout << "size:"<<req.size<<"字节"<<std::endl;
    cout << "----------------------http end---------------------------" << endl;
   

    string respline="HTTP/1.1 200 OK\r\n";//回复的内容
    string respheader=suffixToDesc(req.suffix);//报头
    if(req.size>0)
    {
        respheader+="Content-Length:";
        respheader+=to_string(req.size);
        respheader+="\r\n";

    }
    string respbody;//

    respbody.resize(req.size+1);
    if(!Util::readFile(req.path,&respbody,req.size))
    {
        Util::readFile(html_404,&respbody,req.size);//说明没读取到正确的文件路径，因此就用404来代替
    }
     respheader += "Content-Length: ";
    respheader += std::to_string(respbody.size());
    respheader += "\r\n";
    resp.outmessage+=respline;
    resp.outmessage+=respheader;
    resp.outmessage+="\r\n";//空行
    cout << "----------------------http response start---------------------------" << endl;
    std::cout << resp.outmessage<< std::endl;
    cout << "----------------------http response end---------------------------" << endl;

    resp.outmessage+=respbody;

    return true;

}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    //string serverip = argv[1];
    uint16_t serverport = atoi(argv[1]);

    unique_ptr<Calserver> tcli(new Calserver(Get, serverport));
    tcli->initServer();
    tcli->start();
    return 0;
}